<template>
  <div class="reminder-list">
    <el-card shadow="never" style="border: none">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="通知设置" name="getReminderType">
          <p class="title">通知类型列表</p>
          <el-table
            v-loading="loading"
            style="width: 100%"
            :data="type"
            border
            stripe
          >
            <el-table-column prop="type" label="提醒类型" align="center">
              <template v-slot="{ row }">
                {{ row?.name }}
              </template>
            </el-table-column>
            <el-table-column prop="open" label="是否开启提醒" align="center">
              <template v-slot="{ row }">
                <el-switch
                  v-if="row.reminder"
                  v-model="row.reminder.open"
                  active-color="#13ce66"
                  :active-value="1"
                  :inactive-value="0"
                  @change="handleOpenChange(row.id)"
                />
                <el-switch
                  v-else
                  v-model="row.open"
                  active-color="#13ce66"
                  :active-value="1"
                  :inactive-value="0"
                  @change="handleOpenChange(row.id)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="day" label="提醒天数" align="center">
              <template v-slot="{ row }">
                <!-- <div v-if="!editDay.isEdit"> -->
                <!-- <el-tooltip
                    class="item"
                    effect="dark"
                    content="双击修改"
                    placement="top"
                  > -->
                <span
                  @dblclick="handleEditDay(row)"
                >{{ row?.reminder?.day }}</span>
                <!-- </el-tooltip> -->
                <!-- </div> -->
                <!-- <div v-else>
                  <el-input
                    ref="inputRef"
                    v-model="editDay.day"
                    placeholder="请输入天数"
                    type="number"
                    @keyup.enter.native="handleBlur"
                    @blur="handleBlur"
                  />
                </div> -->
              </template>
            </el-table-column>
            <el-table-column prop="actions" label="操作" align="center">
              <template slot-scope="scope">
                <div class="actions">
                  <el-button
                    circle
                    plain
                    type="primary"
                    icon="el-icon-edit"
                    @click="handleEditApartment(scope.row.reminder)"
                  />
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="通知列表" name="getUserReminderList">
          <div class="sift">
            <span class="notificationLable">通知类型</span>
            <el-select
              v-model="userReminderQuery.type_id"
              placeholder="请选择通知类型"
              @change="changeType()"
            >
              <el-option
                v-for="item in type"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
            <el-button
              class="query"
              type="primary"
              @click="getUserReminderList()"
            >查询</el-button>
          </div>

          <el-table
            v-if="!closeNotice"
            v-loading="loading"
            style="width: 100%"
            :data="list"
            border
            stripe
          >
            <el-table-column
              v-for="(item, index) in options"
              :key="index"
              :prop="item.prop"
              :label="item.label"
              align="center"
            >
              <template
                v-if="item.prop === 'fieldData' || item.prop === 'gender'"
                v-slot="{ row }"
              >
                <div>
                  <span v-if="item.prop === 'fieldData'">
                    {{ getLaborContractEnd(row.fieldData)[0].content }}
                  </span>
                  <el-tag v-if="item.prop === 'gender'">
                    {{ row.gender === 1 ? "男" : "女" }}
                  </el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <span
                  class="button"
                  @click="noReminders(scope.row)"
                >不再提醒</span>
              </template>
            </el-table-column>
          </el-table>
          <div v-if="!closeNotice">
            <Pagination
              :total="userReminderQuery.total"
              :limit="userReminderQuery.paginate"
              @pagination="pagination"
            />
          </div>
          <el-empty
            v-if="closeNotice"
            :image-size="200"
            description="该提醒已关闭..."
          />
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-dialog
      title="编辑"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="30%"
    >
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules">
        <el-form-item label="提醒天数" prop="day">
          <el-input v-model="ruleForm.day" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setReminderClick">确定修改</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import {
  getReminderList,
  setReminderOpen,
  editReminderTime,
  reminderType,
  reminderIgnore
} from '@/api/reminder'
import { userReminder } from '@/api/basic'
import { options } from './js/options'
export default {
  name: 'ReminderList',
  components: {
    Pagination
  },
  data() {
    return {
      closeNotice: false,
      options: options,
      list: [],
      loading: false,
      editDay: {
        isEdit: false,
        day: 0,
        id: null
      },
      flag: false,
      activeTab: 'getReminderType',
      userReminderQuery: {
        time: 10,
        paginate: 10,
        type: 1,
        page: 1,
        total: 0,
        type_id: ''
      },
      type: [],
      type_id: '',
      dialogVisible: false,
      ruleForm: {
        day: '',
        id: ''
      },
      rules: {
        day: [
          { required: true, message: '请输入提醒天数', trigger: ['change', 'blur'] }
        ]
      }
    }
  },
  created() {
    this.getReminderType()
    if (this.$route.query.type) {
      this.userReminderQuery.type_id = this.$route.query.type
      this.activeTab = 'getUserReminderList'
      this.handleTabClick()
    }
  },
  methods: {
    noReminders(row) {
      console.log(row)
      const data = {
        reminder_id: this.userReminderQuery.type_id,
        user_id: row.id
      }
      reminderIgnore(data)
        .then((res) => {
          this.handleTabClick()
        })
        .catch((err) => {})
    },
    getReminderType() {
      reminderType()
        .then((res) => {
          console.log(res, '类型')
          this.type = res.data
          this.userReminderQuery.type_id = res.data[0].id
        })
        .catch((err) => {})
    },
    pagination(e) {
      this.userReminderQuery.paginate = e.limit
      this.userReminderQuery.page = e.page
      this.handleTabClick()
    },
    handleTabClick() {
      this.closeNotice = false
      this[this.activeTab]()
    },
    async getReminderList() {
      this.loading = true
      try {
        const res = await getReminderList()
        console.log(res, '列表')
        this.list = res.data
      } catch (error) {
        this.$message.error(error.message)
      } finally {
        this.loading = false
      }
    },
    async getUserReminderList() {
      this.loading = true
      try {
        const res = await userReminder(this.userReminderQuery)
        this.userReminderQuery.total = res.meta.total
        this.list = res.data
      } catch (error) {
        this.$message.error(error.response.data.message)
        if (error.response.data.message === '该提醒已关闭') {
          this.closeNotice = true
        }
      } finally {
        this.loading = false
      }
    },
    handleOpenChange(type_id) {
      this.setReminderOpenApi(type_id)
    },
    async setReminderOpenApi(type_id) {
      try {
        const res = await setReminderOpen({ type_id })
        if (res.status === 'success') {
          this.$message.success('修改成功')
        }
      } catch (error) {
        this.$message.error('修改失败')
      }
    },
    handleEditDay(row) {
      this.editDay.isEdit = true
      this.editDay.day = row.day
      this.editDay.id = row.id
      this.flag = true
      this.$nextTick(() => {
        this.$refs.inputRef.focus()
      })
    },
    async handleBlur() {
      if (!this.flag) return
      if (!this.editDay.day) return this.$message.error('提醒天数不能为空')
      else if (this.editDay.day <= 0) { return this.$message.error('提醒天数至少为1天') }
      const { day, id } = this.editDay
      await this.editReminderTimeApi({ day, id })
      await this.getReminderType()
      this.flag = false
      this.editDay = this.$options.data().editDay
    },
    async editReminderTimeApi(params) {
      try {
        const res = await editReminderTime(params)
        if (res.status === 'success') {
          this.$message.success('修改成功')
        }
      } catch (error) {
        this.$message.error('修改失败')
      }
    },
    handleEditApartment(params) {
      console.log(params)
      this.ruleForm = {
        day: params?.day,
        id: params?.id
      }
      this.dialogVisible = true
    },
    setReminderClick() {
      try {
        this.$refs.ruleForm.validate(async(validate) => {
          if (!validate) return
          if (this.ruleForm.day > 999 || this.ruleForm.day <= 0) {
            return this.$message.error('提醒天数须在1-999之间')
          }
          const res = await editReminderTime(this.ruleForm)
          this.$message.success(res.message)
          this.getReminderType()
        })
      } catch (error) {
        this.$message.error(error.message)
      } finally {
        this.dialogVisible = false
      }
    },

    getLaborContractEnd(fieldList) {
      return fieldList.filter(item => item?.field?.id === 55)
    }
  }
}
</script>
<style scoped lang='scss'>
.reminder-list {
  background-color: #fff;
  padding: 40px;
  margin: 20px;
  height: 87vh;
  .title {
    height: 100%;
    display: flex;
    justify-content: center;
    font-size: 18px;
    font-weight: bold;
  }
}
.sift {
  margin: 20px 0;
}
.notificationLable {
  margin-right: 10px;
}
.query {
  margin-left: 10px;
}
.button {
  color: #409eff;
  text-decoration: none;
  cursor:pointer;
}
</style>
